package com.hava.spring_data.repository;

import com.hava.spring_data.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by yanfa on 2016/10/26.
 */
@Repository
public class AccountJdbcTemplateDao {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public void resetMoney() {
        System.out.println("resetMoney");
        jdbcTemplate.update("update account set balance=1000");
    }

    public List<Account> accountList() {
        System.out.println("accountList");
        return this.jdbcTemplate.query("select * from account", new RowMapper<Account>() {
            public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                Account account = new Account();
                account.setUser(rs.getString("user"));
                account.setBalance(rs.getDouble("balance"));

                return account;
            }
        });
    }

//    @Transactional(propagation = Propagation.REQUIRED)
    public void transferMoney(String source, String target, double count) {
        System.out.println("transferMoney");
        this.jdbcTemplate.update("update account set balance=balance-? where user=?", count, source);
        throwException();
        this.jdbcTemplate.update("update account set balance=balance+? where user=?", count, target);
    }

    // 应用于事务处理
    private void throwException() {
        throw new RuntimeException("ERROR");
    }
}
